// pages/patrol_record/patrol_record.js
var app = getApp();
var util = require('../../utils/util.js');
var applet_park_api_url = app.globalData.applet_park_api_url;
const {
  requestDataparams
} = require('../../utils/request.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLeader: false,
    currenttype: '',
    checkname: '',
    expectedEndTime1: '',
    expectedStartTime1: '',
    checkTaskId: 1,
    currenttDate: '',
    lists: [],
    id: '',
    list: [{
      // 状态
      id: 0,
      // title
      name: "一楼热水泵房",
      // 时间

    }, {
      id: 1,
      name: "工程-车库-B1F-热水泵房",

    }, {
      id: 2,
      name: "工程-学术报告厅-1F-报告厅低压配电室",

    }

      , {
      id: 3,
      name: "一楼热水泵房",

    }


    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    if (options.checkTaskId) {
      this.data.checkTaskId = options.checkTaskId;
    }
    if (options.name) {
      this.data.checkname = options.name;
    }


    if (options.et) {
      this.data.expectedEndTime1 = options.et;
    }
    if (options.st) {
      this.data.expectedStartTime1 = options.st;
    }
    if (options.id) {
      this.data.id = options.id;
    }
    var date = new Date()
    var year = date.getFullYear()
    var month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
    var day = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()
    this.data.currenttDate = year + '-' + month + '-' + day;
    
    if (options.isLeader) {
      this.data.isLeader = options.isLeader;
    }

    this.setData(this.data)
    this.loadData();
  },
  timePro() {
    this.data.currenttDate = this.getBefOrAft(0, this.data.currenttDate);
    this.setData(this.data)
  },
  timeNaxt() {
    this.data.currenttDate = this.getBefOrAft(1, this.data.currenttDate);
    this.setData(this.data)
  },
  // 获取前天或者后一天  type: 0: 前一天 1：后一天
  getBefOrAft(type, date) {
    let forMatDate = date.replace(/-/g, '/')  // 格式化日期 2019-02-23 => 2019/02/23
    let d = new Date(forMatDate)    // new Date() 不能识别 2019-01-02  需转化为 2019/01/02
    if (type === 0) {
      d = +d - 1000 * 60 * 60 * 24
    } else if (type === 1) {
      d = +d + 1000 * 60 * 60 * 24  // d前面需要加上 +
    }
    d = new Date(d)
    return this.dateFormat(d)  // 格式化 将日期格式转化为我们需要展示格式
  },

  // 格式化日期，传入日期对象   =>2019-01-11  
  dateFormat(date) {
    let y = date.getFullYear()
    let m = date.getMonth() + 1
    let d = date.getDate()
    if (m <= 9) {
      m = '0' + m
    }
    if (d <= 9) {
      d = '0' + d
    }
    return y + '-' + m + '-' + d
  },
  toPartalSCan(e) {
    // if(!this.data.isLeader){
    //   return
    // }
    wx.navigateTo({
      url: '../check_list/check_list?id=' + e.currentTarget.dataset.id + "&checkTaskId=" + this.data.checkTaskId + "&deviceClassificationId=" + e.currentTarget.dataset.did + "&checkname=" + this.data.checkname + '&code=' + e.currentTarget.dataset.code + "&scancode=" + this.data.scancode + '&leaderConfirmed=' + this.data.leaderConfirmed + '&nodeStatus=' + e.currentTarget.dataset.nodestatus + '&isLeader=' + this.data.isLeader + '&checktasknodeid=' + e.currentTarget.dataset.checktasknodeid,
    })
  },
  loadData() {
    var that = this;
    // wx.request({
    //   url: applet_park_api_url + '/api/devices',
    //   method: 'get',

    //   data: {
    //     "checkTaskId": that.data.checkTaskId
    //   },
    //   success: function (res) {
    //     )
    //     if (res.data.code == 0) {
    //       var lists = res.data.data;
    //       that.setData({
    //         lists: lists
    //       })

    //     } else {
    //       wx.showToast({
    //         title: res.data.msg,
    //         icon: 'none'
    //       });
    //     }
    //   },
    //   fail: function (res) {
    //     )
    //     wx.showToast({
    //       title: '网络异常，请稍后重试',
    //     })
    //   }
    // })


    requestDataparams('/api/devices', { "checkTaskId": that.data.checkTaskId}, 'GET').then(res => {
      if (res.data.code == 0) {
        var lists = res.data.data;
        that.setData({
          lists: lists
        })

      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.showToast({
        title: '网络异常，请稍后重试',
      })
    });
  },
  selecttype(e) {
    this.setData({
      currenttype: e.currentTarget.dataset.index
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.loadData();
    wx.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 2000
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 获取前天或者后一天  type: 0: 前一天 1：后一天
  getBefOrAft(type, date) {
    let forMatDate = date.replace(/-/g, '/')  // 格式化日期 2019-02-23 => 2019/02/23
    let d = new Date(forMatDate)    // new Date() 不能识别 2019-01-02  需转化为 2019/01/02
    if (type === 0) {
      d = +d - 1000 * 60 * 60 * 24
    } else if (type === 1) {
      d = +d + 1000 * 60 * 60 * 24  // d前面需要加上 +
    }
    d = new Date(d)
    return this.dateFormat(d)  // 格式化 将日期格式转化为我们需要展示格式
  },

  // 格式化日期，传入日期对象   =>2019-01-11  
  dateFormat(date) {
    let y = date.getFullYear()
    let m = date.getMonth() + 1
    let d = date.getDate()
    if (m <= 9) {
      m = '0' + m
    }
    if (d <= 9) {
      d = '0' + d
    }
    return y + '-' + m + '-' + d
  },
  bindKeyInput: function (e) {
    this.data[e.currentTarget.dataset.inputname] = e.detail.value;


    this.setData(this.data);
  },

  submit(e) {
    var that = this;
    if (that.data.isleader) {

      return
    }
    if (!that.data.content) {
      wx.showToast({
        title: '确认内容不能为空',
        icon: 'success',
        duration: 2000
      })
      return
    }
    var uid = wx.getStorageSync("id");
    let url = '/api/checkTasks/' + that.data.id + '/confirm?confirmedBy=' + uid + '&confirmationContent=' + that.data.content;
    // wx.request({
    //   url: applet_park_api_url + '/api/checkTasks/' + that.data.id + '/confirm?confirmedBy=' + uid + '&confirmationContent=' + that.data.content,
    //   // / api / checkTasks / 巡检任务ID / confirm ? confirmedBy = 确认人（当前登录用户ID）&confirmationContent=确认内容
    //   method: 'PUT',
    //   header: {
    //     contentType: "application/json",
    //   },
    //   success: function (res) {
    //     )
    //     if (res.data.code == 0) {
    //       wx.showToast({
    //         title: '保存成功',
    //         icon: 'success',
    //         duration: 2000
    //       })


    //       var pages = getCurrentPages();
    //       var prevPage = pages[pages.length - 2]; //上一个页面
    //       prevPage.loadData();
    //       wx.navigateBack();


    //     } else {
    //       wx.showToast({
    //         title: res.data.msg,
    //         icon: 'none'
    //       });
    //     }
    //   },
    //   fail: function (res) {
    //     wx.showToast({
    //       title: '网络异常',
    //     });
    //   }

    // })
    requestDataparams(url, {}, 'PUT').then(res => {
      if (res.data.code == 0) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        })


        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面
        prevPage.loadData();
        wx.navigateBack();


      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        });
      }
    }).catch(err => {
      
    });
  },
  scan: function () {
    let lists = this.data.lists;
    var that = this;
    // that.submitPra();
    wx.scanCode({
      success(res) {
        

        if (res.result) {
          var hasNode = false;
          for (let i in lists) {
            if (lists[i].code == res.result) {
              hasNode = true;

              // if (lists[i].nodeStatus == 2) {
              //   wx.showToast({
              //     title: '当前节点已巡检过',
              //     icon: 'none',
              //     duration: 2000
              //   })
              //   return
              // }
              // lists[i].nodeStatus = 2;
              lists[i].currentcode = '[当前]'
              // that.data.locationsid = lists[i].id;
              that.data.scancode = res.result;
              that.setData(that.data);
          

            } else {
              lists[i].currentcode = ''
            }
          }

          if (!hasNode) {
            wx.showToast({
              title: '任务设备和当前设备不匹配，请选择正确设备',
              icon: 'none',
              duration: 2000
            })
          }

        }
      },
      fail() {
        wx.showToast({
          title: '扫描失败',
          icon: 'fail',
          duration: 3000
        })
      }
    })
  },
})